package com.search.service.Impl;

import com.common.domain.Product;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.search.dao.ProductDao;
import com.search.service.ProductService;
import com.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-02 9:19
 * @description
 * @copyright 2021
 */
@Service
public class SearchServiceImpl implements SearchService {

  @Resource private ElasticsearchTemplate elasticsearchTemplate;

  @Autowired private ProductDao productDao;

  @Autowired private ProductService productService;

  @Autowired private ObjectMapper objectMapper;

  @Override
  public List<Product> searchProducts(String query, Integer page, Integer rows) {
    SearchQuery builder =
        new NativeSearchQueryBuilder()
            .withQuery(
                multiMatchQuery(query, "productName", "productCategory", "productDescription"))
            .withPageable(PageRequest.of(page - 1, rows))
            .build();

    return this.elasticsearchTemplate.queryForList(builder, Product.class);
  }

  @Override
  public void createIndex(Class<? extends Object> type) {
    //    创建索引
    elasticsearchTemplate.createIndex(type);
    //    创建Mapping
    elasticsearchTemplate.putMapping(type);
    //    添加文档
    List<Product> products = productService.queryProducts();
    if (products.isEmpty()) {
      return;
    }
    this.addProducts(products);
  }

  @Override
  public void deleteIndex(String indexName) {
    elasticsearchTemplate.deleteIndex(indexName);
  }

  @Override
  public void deleteIndex(Class<?> type) {
    elasticsearchTemplate.deleteIndex(type);
  }

  @Override
  public void addProducts(List<Product> products) {
    productDao.saveAll(products);
  }

  @Override
  public void addProduct(Product product) {
    productDao.save(product);
  }

  @Override
  public void deleteProduct(Product product) {
    elasticsearchTemplate.delete(Product.class, product.getProductId());
  }
}
